import React, {useEffect, useState} from 'react';
import {
    Breadcrumb,
    Button,
    Col,
    Form,
    Input,
    Layout,
    message,
    Modal,
    Popconfirm,
    Row,
    Select,
    Space,
    Switch,
    Tag
} from "antd";
import {Content} from "antd/es/layout/layout";
import {useNavigate, useParams} from "react-router-dom";
import Mytable from "../../../../pages/Mytable";
import {getAllTaskByPage, deleteTaskById, modifyTaskById, addTask, getTaskById,runTask} from '../../../../api/task'
import {getModulesByList, getSystemModuleBySystemId} from '../../../../api/systemModule'
import {ExclamationCircleOutlined, PlayCircleOutlined} from "@ant-design/icons";
import {getSystemsBySystemId} from "../../../../api/systemInfo";

const {CheckableTag} = Tag;
const {Option} = Select;

function Index_bak(props) {
    const {id} = useParams()
    const navigate = useNavigate()
    const [total, setTotal] = useState(0);
    const [moduleVisible, setModuleVisible] = useState(false);
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [runTaskModalVisible, setRunTaskModalVisible] = useState(false);
    const [moduleList, setModuleList] = useState([]);
    const [systemInfoList, setSystemInfoList] = useState([]);
    const [modules, setModules] = useState([]);
    const [edit, setEdit] = useState(false);
    const [task, setTask] = useState({
        "system_id": Number(id),
        "task_name": ''
    })
    const [taskForm] = Form.useForm();
    const [searchForm] = Form.useForm();
    const [runTaskForm] = Form.useForm();
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(false);
    const [page, setPage] = useState({
        "current": 1,
        "pageSize": 10
    })
    const pagination = {
        onShowSizeChange: (current, pageSize) => {
            paginationChange(current, pageSize)
        },
        onChange: (current, pageSize) => {
            paginationChange(current, pageSize)
        },
        showSizeChanger: true,
        total,
        current: page.current,
        pageSize: page.pageSize,
        defaultPageSize: 10,
        pageSizeOptions:
            [5, 10, 15, 20]
    }
    const paginationChange = async (current, pageSize) => {
        setPage({
            pageSize,
            current
        })
    }
    useEffect(() => {
        setLoading(true)
        getAllTaskByPage({...page, ...task}).then(response=>{
            const {data: res} = response
            const {total, records} = res.data
            setTotal(total)
            setData(records)
            setLoading(false)
        })
    }, [page, task]);

    useEffect(() => {
        getSystemModuleBySystemId(id).then(response => {
            const {data: res} = response
            setModules(res['data'])
        })
        getSystemsBySystemId(id).then(response => {
            const {data: res} = response
            setSystemInfoList(res['data'])
        })
        // eslint-disable-next-line
    }, [])

    const deleteTask = (id) => {
        return async () => {
            const {data: res} = await deleteTaskById(id)
            message.success(res['msg'])
            setPage({...page, current: 1})
        }
    }

    const changePigeonhole =  (task) => {
        return async (checked,event) => {
            Modal.confirm({
                title: '确认提示',
                icon: <ExclamationCircleOutlined/>,
                content: '确定要归档吗？',
                okText: '确认',
                cancelText: '取消',
                onOk: async () => {
                    task['is_pigeonhole'] = 1
                    const {data: res} = await modifyTaskById(task)
                    message.success(res['msg'])
                    setPage({...page,current: 1})
                }, // 点击确定时要执行的事件
                onCancel: () => {
                    task['is_pigeonhole'] = 0
                    return
                },
            });
        }
    }

    const columns = [
        {
            title: '任务名称',
            width: "80vh",
            dataIndex: 'task_name',
        },
        {
            title: '是否归档',
            dataIndex: 'is_pigeonhole',
            render: (_, record) => (<Space>
                <Switch checkedChildren="已归档" unCheckedChildren="未归档" checked={record['is_pigeonhole'] === 1}
                        disabled={record['is_pigeonhole'] === 1}
                        onClick={changePigeonhole(record)}/>
            </Space>)
        },
        {
            title: '运行任务',
            dataIndex: 'is_pigeonhole',
            render: (_, record) => (<Space align={"center"}>
               <Button size={'large'} type={'text'} onClick={()=>{
                   runTaskForm.setFieldsValue({type:"interface",task_id:record.id,system_id:Number(id)})
                   setRunTaskModalVisible(true)
               }}><PlayCircleOutlined style={{color:"green"}}/></Button>
            </Space>)
        },
        {
            title: '操作',
            dataIndex: 'repayment',
            render: (_, record) => (<Space>
                <Popconfirm placement="top" title={"是否删除该任务"} onConfirm={deleteTask(record.id)}
                            disabled={record['is_pigeonhole'] === 1} okText="确认" cancelText="取消">
                    <Button type='danger' disabled={record['is_pigeonhole'] === 1}>删除任务</Button>
                </Popconfirm>
                <Button type='primary' disabled={record['is_pigeonhole'] === 1} onClick={async () => {
                    const {data: res} = await getTaskById(record.id)
                    let {data} = res
                    data['task_module'] = JSON.parse(`[${data['task_module']}]`)
                    taskForm.setFieldsValue(data)
                    setEdit(true)
                    setIsModalVisible(true)
                }}>编辑任务</Button>
                <Button type='primary' disabled={record['is_pigeonhole'] === 1} onClick={async () => {
                    navigate(`/main/editTaskSuit/${id}/${record.id}`,{state:{ids:JSON.parse(`[${record['task_module']}]`)}})
                }}>添加测试套件</Button>
                <Button onClick={async () => {
                    const ids = JSON.parse(`[${record['task_module']}]`)
                    const {data: res} = await getModulesByList({system_id: Number(id), ids})
                    setModuleList(res.data)
                    setModuleVisible(true)
                }}>查看关联模块</Button>
            </Space>)
        }
    ];
    return (
        <Layout style={{padding: '0 24px 24px'}}>
            <Breadcrumb style={{margin: '16px 0'}}>
                <Breadcrumb.Item onClick={() => navigate("/main")}>首頁</Breadcrumb.Item>
                <Breadcrumb.Item onClick={() => navigate("/main/task")}>任务管理</Breadcrumb.Item>
                <Breadcrumb.Item>编辑任务</Breadcrumb.Item>
            </Breadcrumb>
            <Content
                className="site-layout-background"
                style={{
                    padding: 24,
                    margin: 0,
                    minHeight: 280,
                }}
            >
                <Form
                    name="basic"
                    autoComplete="off"
                    form={searchForm}
                    style={{
                        marginBottom: '10px'
                    }}
                    onFinish={(values) => {
                        setTask({...values, system_id: Number(id)})
                        setPage({...page, current: 1})
                    }}
                >
                    <Row gutter={24}>
                        <Col span={6}><Form.Item
                            label="任务名称"
                            name='task_name'
                        >
                            <Input/>
                        </Form.Item></Col>
                        <Col span={18} style={{
                            textAlign: 'right',
                        }}>
                            <Space>
                                <Button type="primary" onClick={() => setIsModalVisible(true)}>
                                    添加任务
                                </Button>
                                <Button type="primary" htmlType="submit">
                                    查询
                                </Button>
                                <Button
                                    onClick={async () => {
                                        searchForm.resetFields();
                                        const formValue = await searchForm.validateFields()
                                        setTask({...task, ...formValue})
                                        setPage({...page, current: 1})
                                    }}
                                >
                                    重置
                                </Button>
                            </Space>
                        </Col>
                    </Row>
                </Form>
                <Mytable
                    columns={columns}
                    dataSource={data}
                    pagination={pagination}
                    bordered
                    loading={loading}
                />
                <Modal
                    title="查看关联模块"
                    centered
                    visible={moduleVisible}
                    okText={"确认"}
                    onCancel={() => setModuleVisible(false)}
                    footer={null}
                >
                    {moduleList.map((module) => {
                        return <CheckableTag
                            key={module['id']}
                            checked
                        >
                            {module['module_name']}
                        </CheckableTag>
                    })}
                </Modal>
                <Modal title={edit ? '编辑任务' : '添加任务'} visible={isModalVisible} closable={false} footer={null}>
                    <Form
                        name="basic"
                        autoComplete="off"
                        layout={'vertical'}
                        form={taskForm}
                        onFinish={async (values) => {
                            let {task_module} = values
                            task_module = task_module ? JSON.stringify(task_module) : ""
                            if (edit) {
                                const {data: res} = await modifyTaskById({
                                    ...values,
                                    task_module: task_module.substring(1, task_module.length - 1)
                                })
                                message.success(res['msg'])
                            } else {
                                const {data: res} = await addTask({
                                    ...values,
                                    system_id: Number(id),
                                    task_module: task_module.substring(1, task_module.length - 1)
                                })
                                message.success(res['msg'])
                            }
                            setIsModalVisible(false)
                            setEdit(false)
                            taskForm.resetFields()
                            setPage({...page})
                        }}
                    >
                        <Form.Item
                            label="id"
                            name="id"
                            style={{display: 'none'}}
                        >
                            <Input/>
                        </Form.Item>
                        <Form.Item
                            label="system_id"
                            name="system_id"
                            style={{display: 'none'}}
                        >
                            <Input/>
                        </Form.Item>
                        <Form.Item
                            label="任务名称"
                            name="task_name"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入任务名称',
                                },
                            ]}
                        >
                            <Input placeholder="请输入任务名称"/>
                        </Form.Item>
                        <Form.Item
                            label="关联模块"
                            name="task_module"
                        >
                            <Select
                                mode="multiple"
                                allowClear
                                style={{
                                    width: '100%',
                                }}
                                placeholder="请选择关联模块"
                            >
                                {modules.map((module) => {
                                    return <Option key={module['id']}
                                                   value={module['id']}>{module['module_name']}</Option>
                                })}
                            </Select>
                        </Form.Item>
                        <Form.Item
                            wrapperCol={{
                                offset: 8,
                                span: 16,
                            }}
                        ><Space>
                            <Button type="primary" htmlType="submit">
                                提交
                            </Button>
                            <Button type="default" onClick={async () => {
                                setIsModalVisible(false)
                                taskForm.resetFields()
                                setEdit(false)
                            }}>
                                取消
                            </Button>
                        </Space>
                        </Form.Item>
                    </Form>
                </Modal>
                <Modal title={'运行任务'} visible={runTaskModalVisible} closable={false} footer={null}>
                    <Form
                        name="basic"
                        autoComplete="off"
                        layout={'vertical'}
                        form={runTaskForm}
                        onFinish={async (values) => {
                            console.log(values)
                            const {data:res} = await runTask(values)
                            setRunTaskModalVisible(false)
                            runTaskForm.resetFields()
                            message.success(res['msg'])
                        }}
                    >
                        <Form.Item
                            label="task_id"
                            name="task_id"
                            style={{display: 'none'}}
                        >
                            <Input/>
                        </Form.Item>
                        <Form.Item
                            label="system_id"
                            name="system_id"
                            style={{display: 'none'}}
                        >
                            <Input/>
                        </Form.Item>
                        <Form.Item
                            label="type"
                            name="type"
                            style={{display: 'none'}}
                        >
                            <Input/>
                        </Form.Item>
                        <Form.Item
                            label="任务名称"
                            name="task_name"
                            rules={[
                                {
                                    required: true,
                                    message: '请选择任务名称',
                                },
                            ]}
                        >
                            <Input placeholder="请输入任务名称"/>
                        </Form.Item>
                        <Form.Item
                            label="选择环境"
                            name="system_info_id"
                            rules={[
                                {
                                    required: true,
                                    message: '请选择测试环境',
                                },
                            ]}
                        >
                            <Select
                                allowClear
                                style={{
                                    width: '100%',
                                }}
                                placeholder="请选择测试环境"
                            >
                                {systemInfoList.map((system) => {
                                    return <Option key={system['id']}
                                                   value={system['id']}>{system['info_name']}</Option>
                                })}
                            </Select>
                        </Form.Item>
                        <Form.Item
                            label="任务描述"
                            name="description"
                        >
                            <Input placeholder="请输入任务描述"/>
                        </Form.Item>
                        <Form.Item
                            wrapperCol={{
                                offset: 8,
                                span: 16,
                            }}
                        ><Space>
                            <Button type="primary" htmlType="submit">
                                提交
                            </Button>
                            <Button type="default" onClick={async () => {
                                runTaskForm.resetFields()
                                setRunTaskModalVisible(false)
                            }}>
                                取消
                            </Button>
                        </Space>
                        </Form.Item>
                    </Form>
                </Modal>
            </Content>
        </Layout>
    );
}

export default Index_bak;